const crypto = require('crypto');
const path = require('path');
const fs = require('fs');
// const rs = require('jsrsasign');
const privateKey = fs.readFileSync(path.join(__dirname, './pem/myPrivate.pem'), "utf8");
const publicKey = fs.readFileSync(path.join(__dirname, './pem/myPublic.pem'), "utf8");

const algorithm = 'aes-128-cbc';

crypto.aes128Encrypt = function (text, password, iv) {
  if (!text) return null;
  let buf;
  if (Buffer.isBuffer(text)) {
    buf = text;
  } else {
    buf = Buffer.from(text);
  }
  try {
    const cipher = crypto.createCipheriv(algorithm, password, iv);
    const encrypted = cipher.update(buf);
    return Buffer.concat([encrypted, cipher.final()]);
  } catch (err) {
    throw err;
  }
};
// 公钥解密
crypto.rsaPublicDecrypt = function (encryptStr) {
  try {
    const cryptoPacked = crypto.publicDecrypt({
      key: publicKey,
      padding: crypto.constants.RSA_PKCS1_PADDING
    }, Buffer.from(encryptStr, 'base64'));
    return cryptoPacked;
  } catch (error) {
    return ''
  }
};
// 公钥加密
crypto.rsaPublicEncrypt = function (encryptStr) {
  const cryptoPacked = crypto.publicEncrypt({
    key: publicKey,
    // oaepHash: 'SHA256',
    padding: crypto.constants.RSA_PKCS1_PADDING
  }, Buffer.from(encryptStr));

  return cryptoPacked.toString("base64");
};
// 私钥解密
crypto.rsaDecrypt = function (arr) {
  if (!arr) return ''
  if (!Array.isArray(arr)) arr = Buffer.from(arr, 'base64');
  try {
    return crypto.privateDecrypt({
      key: privateKey,
      // oaepHash: 'SHA256',
      padding: crypto.constants.RSA_PKCS1_PADDING
    }, arr);
  } catch (error) {
    console.log(error)
    return ''
  }
};
// 私钥加密
crypto.rsaEncrypt = function (arr) {
  return crypto.privateEncrypt({
    key: privateKey,
    padding: crypto.constants.RSA_PKCS1_PADDING
  }, Buffer.from(arr)).toString("base64");
};
// 私钥加密，大文本，或者使用 privateEncrypt 把 padding 参数改为 crypto.constants.RSA_NO_PADDING
// 但是前端不支持 RSA_NO_PADDING 解密
crypto.rsaEncryptLargeText = function (encryptStr) {
  if (typeof encryptStr !== 'string') throw new Error('参数必须是字符串');
  const sliceStr = function (str) {
    const arr = [];
    const length = str.length;
    const itemLength = 100;
    const num = Math.ceil(length / itemLength);
    for (let i = 0; i < num; i++) {
      arr.push(str.slice(i * itemLength, (i + 1) * itemLength));
    }
    return arr;
  };

  const cryptoData = function (arr) {
    const cryptoedArr = [];
    for (const item of arr) {
      const buf = Buffer.from(item);
      const cryptoed = crypto.privateEncrypt({
        key: privateKey,
        padding: crypto.constants.RSA_PKCS1_PADDING
      }, buf);
      cryptoedArr.push(cryptoed.toString("base64"));
    }
    return cryptoedArr;
  };
  return cryptoData(sliceStr(encryptStr));
};;

crypto.base64 = function (param) {
  return Buffer.from(param).toString('base64');
};

crypto.unbase64 = function (base64) {
  return Buffer.from(base64, 'base64');
};
// crypto.Sha1Salt = function (text) {
//   if (!text) {
//     return '';
//   }
//   const sha1 = crypto.createHash('sha1').update(text).digest('hex');

//   const key = rs.KEYUTIL.getKey(merchantPrivateKey);
//   // 创建 Signature 对象，设置签名编码算法
//   const signature = new rs.KJUR.crypto.Signature({ alg: "SHA256withRSA" });
//   // 初始化
//   signature.init(key);

//   signature.updateString(sha1);
//   // 生成密文
//   const originSign = signature.sign();

//   return rs.hextob64(originSign);
// };
module.exports = crypto;